package instance

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"github.com/student414/ddns/param"
	yaml "gopkg.in/yaml.v2"
)

type httpGetState int

const httpGetStateFailed = 0
const httpGetStateSuccessed = 1

type TypeHttpGet struct {
	DdnsInstanceBase

	URL  string `yaml:"url"`
	Loop int64  `taml:"loop"`

	oldURL   string
	oldState httpGetState // 0->failed 1->succesd
}

func (d *TypeHttpGet) Parse(content []byte) error {
	err := d.DdnsInstanceBase.Parse(content)
	if nil != err {
		return err
	}

	err = yaml.Unmarshal(content, d)
	if nil != err {
		return err
	}

	return nil
}

func (d *TypeHttpGet) Run() error {
	for {
		if ok := d.DdnsInstanceBase.Run(); nil != ok {
			fmt.Printf("[WARN  ]\t%s\n", "Instance disabled !")

			return nil
		}

		// run once
		err := func() error {
			// check ip change
			var urlCopy string = d.URL
			for _, p := range param.ParamList {
				urlCopy = strings.Replace(urlCopy, p.GetKeyword(), p.GetValue(), -1)
			}

			if d.oldURL == urlCopy && d.oldState == httpGetStateSuccessed {
				fmt.Printf("[WARN  ]\t%s\n", "Not changed !")
			} else {
				d.oldURL = urlCopy

				fmt.Printf("[VISIT ]\t%s\n", urlCopy)

				// Http
				client := http.Client{}
				resp, err := client.Get(urlCopy)
				if nil != err {
					return err
				}

				data, err := ioutil.ReadAll(resp.Body)
				if err != nil {
					return err
				}

				fmt.Printf("[RESULT]\t%s\n", string(data))
			}

			return nil
		}()

		if nil != err {
			println(err.Error())
			d.oldState = httpGetStateFailed
		} else {
			d.oldState = httpGetStateSuccessed
		}

		// record time
		lastRunTime := time.Now().Unix()

		// check loop
		if d.Loop <= 0 {
			break
		}

		for {
			time.Sleep(time.Second * 10)
			if time.Now().Unix()-lastRunTime >= d.Loop {
				break
			}
		}
	}

	return nil
}
